/*
 * Author: Digital Zoom Studio
 * Website: http://digitalzoomstudio.net/
 * Portfolio: http://codecanyon.net/user/ZoomIt/portfolio
 */

(function($) {
	$.fn.scrollergallery = function(o) {

		var defaults = {
                    scrollerSettings : {}
                    ,galleryType : "scroller"
                    ,settings_fullwidth : 'off'
                    ,settings_fullwidthHack : 'off'
                    ,layout : 'masonry'
                    ,innerWidth : '0'
                };
		var o = $.extend(defaults, o);

		this.each( function() {
                        
                        o.innerWidth = parseInt(o.innerWidth, 10);
			//console.log(this);
			var totalWidth=0
			,totalHeight=0
                        ,comWidth=0
			,comHeight=0
                        ,origOffsetX = 0
                        ,origWindowW = 0
                        ;
			var cthis = jQuery(this)
			,inner
			,inners
                        ,parorcon
                        ,arrows_innerPoints = []
                        ,arrows_currPos = 0
                        ,arrows_currAPos = 0
                        ;
                        //variables for determining the availability of slides to perform transition
			var busy=false
			,busyArray = []
                        ,started=false
                        ;
                        
                        var nrLoaded = 0
                        ,nrChildren
                        ;
                        
                        var arrowPadding = 50
                        ;
			var easing = "linear";
                        var i=0;
                        
                        init();
                        function init(){
                           inner = cthis.find('.inner').eq(0);
                           if(o.innerWidth!=0){
                               inner.css('width', o.innerWidth);
                           }
                           nrChildren = inner.children().length;
                           inner.children().each(function(){
                               var _t = jQuery(this);
                               var toload;
                               if(_t.hasClass('sgitem-tobe')){
                                   _t.removeClass('sgitem-tobe');
                                   _t.addClass('sgitem');
                                   var aux = '';
                                   if(_t.attr('data-type')=='image'){
                                       aux = '<img src="'+_t.attr('data-src')+'"/>';
                                       _t.prepend(aux);
                                   }
                                   if(_t.attr('data-type')=='imageandlink'){
                                       aux = '<a href="' + _t.attr('data-link')+'">';
                                       aux += '<img src="'+_t.attr('data-src')+'"/>';
                                       aux += '</a>';
                                       _t.prepend(aux);
                                   }
                                   if(_t.attr('data-type')=='imageandprettyphoto'){
                                        aux = '<a href="' + _t.attr('data-link')+'" rel="prettyPhoto';
                                        if(_t.attr('data-prettyPhotoGallery')!=undefined && _t.attr('data-prettyPhotoGallery')!=''){
                                            aux+='[' + _t.attr('data-prettyPhotoGallery')  + ']';
                                        }
                                        aux+='">';
                                       
                                       
                                       aux += '<img src="'+_t.attr('data-src')+'"/>';
                                       aux += '</a>';
                                       _t.prepend(aux);
                                   }
                               }
                               if(_t.get(0).nodeName=="IMG"){
                                   toload = _t.get(0);
                               }else{
                                   toload = _t.find('img').eq(0).get(0);
                               }
                               if(toload==undefined){
                                   imageLoaded();
                               }else{
                                   if(toload.complete==true && toload.naturalWidth != 0){
                                       imageLoaded();
                                   }else{
                                       jQuery(toload).bind('load', imageLoaded);
                                   }
                               }
                               
                                   
                           })
                           setTimeout(handleReady, 5000); //failsafe in case the image loading 
                        }
                        function imageLoaded(e){
                            nrLoaded++;
                            if(nrLoaded >= nrChildren){
                                handleReady();
                            }
                        }
                        //function which starts the script
                        function handleReady(){
                            if(started==true){
                                return;
                            }
                            started=true;
                            if(o.layout=='masonry'){
                            inner.masonry();
                            }
                            comWidth = inner.width();
                            
                            if(o.type=="scroller"){
                                init_scroller();
                            }else{
                                init_arrows();
                            }
                        }
                        function init_scroller(){
                            cthis.scroller(o.scrollerSettings);
                            stylizeGallery();
                        }
                        function init_arrows(){
                            cthis.addClass('type-arrows');
                            inner = cthis.find('.inner').eq(0);
                            inner.wrap('<div class="inners"></div>');
                            inners = cthis.children('.inners');
                            
                            var auxa = [];
                            var aux = 0;
                            inner.children().each(function(){
                                var _t = jQuery(this);
                                //console.log(_t.css('top'));
                                if(parseInt(_t.css('top'), 10)==0){
                                    auxa.push(parseInt(_t.css('left'), 10));
                                }
                            })
                            for(i=auxa.length-1;i>0;i--){
                                aux = -auxa[i];
                                arrows_innerPoints.push(aux);
                            }
                            arrows_innerPoints.push(0)
                            var i2=auxa.length-1;
                            for(i=1;i<auxa.length;i++){
                                aux = comWidth - auxa[i2];
                                arrows_innerPoints.push(aux)
                                i2--;
                            }
                            arrows_currAPos = parseInt(arrows_innerPoints.length/2,10);
                            
                            inners.append(inner.clone());
                            inners.append(inner.clone());
                            inners.children().eq(0).find('div.sgitem[data-type=imageandprettyphoto]').each(function(){
                                var _t = jQuery(this);
                                if(_t.attr('data-prettyPhotoGallery')!=undefined && _t.attr('data-prettyPhotoGallery')!=''){
                                    _t.children('a').attr('rel', (_t.children('a').attr('rel') + '1'));
                                }
                            });
                            inners.children().eq(1).find('div.sgitem[data-type=imageandprettyphoto]').each(function(){
                                var _t = jQuery(this);
                                if(_t.attr('data-prettyPhotoGallery')!=undefined && _t.attr('data-prettyPhotoGallery')!=''){
                                    _t.children('a').attr('rel', (_t.children('a').attr('rel') + '2'));
                                }
                            });
                            inners.children().eq(2).find('div.sgitem[data-type=imageandprettyphoto]').each(function(){
                                var _t = jQuery(this);
                                if(_t.attr('data-prettyPhotoGallery')!=undefined && _t.attr('data-prettyPhotoGallery')!=''){
                                    _t.children('a').attr('rel', (_t.children('a').attr('rel') + '3'));
                                }
                            });
                            if(o.layout=='masonry'){
                                inners.children().addClass('masonry');
                            }
                            inners.children().eq(0).css('left', -comWidth);
                            inners.children().eq(1).css('left', 0);
                            inners.children().eq(2).css('left', comWidth);
                            
                            cthis.append('<div class="arrowleft-con"><div class="arrowleft"></div></div>');
                            cthis.append('<div class="arrowright-con"><div class="arrowright"></div></div>');
                            
                            
                            //the default padding for the arrows
                            arrows_currPos = arrowPadding;
                            inners.css('left', arrows_currPos);
                            
                            if(o.settings_fullwidth == 'on'){
                                totalWidth = jQuery(window).width();
                            }
                            
                            //if its fullwidth we add the listener and trigger an initial load
                            
                            if(o.settings_fullwidthHack=='on'){
                                origOffsetX = cthis.offset().left;
                                origWindowW = jQuery(window).width();
                                //cthis.css('left', -cthis.offset().left);
                            }
                            if(o.settings_fullwidth == 'on'){
                                jQuery(window).bind('resize', handleResize);
                                handleResize();
                            }
                            cthis.find('.arrowright-con').bind('click', handleArrowRightClick)
                            cthis.find('.arrowleft-con').bind('click', handleArrowLeftClick)
                            stylizeGallery();
                        }
                        function handleArrowLeftClick(){
                            //console.log(arg);
                            var tempNr = arrows_currAPos;
                            tempNr++;
                            if(tempNr>=arrows_innerPoints.length){
                                arrows_reblock();
                            }else{
                                arrows_gotoPosition(tempNr);
                            }
                        }
                        function handleArrowRightClick(){
                            //console.log(arg);
                            
                            
                            
                            var tempNr = arrows_currAPos;
                            tempNr--;
                            if(tempNr<0){
                                arrows_reblock();
                            }else{
                                arrows_gotoPosition(tempNr);
                            }
                        }
                        function arrows_reblock(){
                            if(busy==true){
                                return;
                            }
                            if(arrows_currAPos==0){
                                arrows_currPos+=comWidth;
                                inners.css('left', arrows_currPos);
                            }
                            //console.log(arrows_currAPos, arrows_innerPoints.length);
                            if(arrows_currAPos>=arrows_innerPoints.length-1){
                                
                                arrows_currPos-= comWidth;
                                //console.log(arrows_currPos)
                                inners.css('left', arrows_currPos);
                            }
                            arrows_gotoPosition(parseInt(arrows_innerPoints.length/2,10));
                        }
                        function arrows_gotoPosition(arg){
                            if(busy==true){
                                return;
                            }
                            busy=true;
                            arrows_currAPos = arg;
                            inners.animate({
                                'left' : arrows_innerPoints[arg] + arrowPadding
                            }, {queue:false, complete:unbusy})
                            arrows_currPos = arrows_innerPoints[arg] + arrowPadding;
                            arrows_currAPos = arg;
                        }
                        function unbusy(){
                            busy = false;
                            
                        }
                        function stylizeGallery(){
                            
                            if(cthis.parent().hasClass('scroller-gallery-con')){
                                parorcon = cthis.parent();
                                parorcon.children('.preloader').fadeOut("slow");
                                
                            }
                            if(cthis.css('opacity') == 0){
                                cthis.animate({
                                        'opacity' : 1
                                    }, 600)
                            }
                            
                            if(o.settings_prettyPhoto=='on'){
                                if(jQuery.fn.prettyPhoto){
                                cthis.find("a[rel^='prettyPhoto']").prettyPhoto();
                                }
                            }
                            if(cthis.find('.real-inner').length==1){
                                inner = cthis.find('.real-inner');
                            }
                            //we add classes for the icons to show
                            for(i=0;i<nrChildren;i++){
                                busyArray[i]=false;
                            }
                            cthis.find('.inner').children().each(function(){
                                
                                var auxtype="page";
                                var curr = jQuery(this);
                                        if(curr.hasClass('a-image')){
                                        auxtype='image';
                                        }
                                        if(curr.hasClass('a-video')){
                                        auxtype='video';
                                        }
                                        curr.find('.desc').children('div').append('<div class="icon '+auxtype+'"></div>');
                                curr.find('.fake-link').click(function(){
                                    curr.children('a').trigger('click');
                                })

                            })
                            
                            cthis.find('.inner').children().mouseover(function(e){
                                var dir="left";
                                var ind = ($(this).parent().children().index($(this)));
                                /*if you want direction scrolling uncomment this*/
                                //if(e.pageX > $(this).offset().left + $(this).width()/2)
                                //dir="right";
                                if(dir=="left"){
                                if(busyArray[ind]==false){
                                $(this).find('.desc').css({
                                        'left' : '-100%'
                                });
                                }
                                }else{
                                if(busyArray[ind]==false){
                                $(this).find('.desc').css({
                                        'left' : '100%'
                                });
                                }
                                }
                                $(this).find('.desc').animate({
                                        'left' : 0
                                }, {duration:300, queue:false, complete:animComplete, easing:easing});
                                busyArray[ind]=true;
                            })
                            cthis.find('.inner').children().mouseout(function(e){
                                var dir="left";
                                var ind = ($(this).parent().children().index($(this)));

                                //if(e.pageX > $(this).offset().left + $(this).width()/2)
                                //dir="right";

                                if(dir=="left"){
                                $(this).find('.desc').animate({
                                        'left' : '100%'
                                }, {duration:300, queue:false, complete:animComplete, easing:easing});
                                }else{
                                $(this).find('.desc').animate({
                                        'left' : '-100%'
                                }, {duration:300, queue:false, complete:animComplete, easing:easing});

                                }
                                busyArray[ind]=true;
                            })
                        }
                        function handleResize(){
                            if(o.settings_fullwidth == 'on'){
                                totalWidth = jQuery(window).width();
                                cthis.width(totalWidth);
                            }
                            
                            if(o.settings_fullwidthHack=='on'){
                                aux = 0;
                                aux = origOffsetX + ( jQuery(window).width() - origWindowW)/2;
                                if(aux<0){
                                    aux = 0
                                }
                                cthis.css('left', -aux);
                            }
                            
                        }
			function animComplete(){
				var ind = ($(this).parent().parent().children().index($(this).parent()));
				//console.log('ceva');
				busyArray[ind]=false;
			}
			return this;
		});
	};
})(jQuery);